package com.leetcode.No0870;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @program: Solution
 * @description: 优势洗牌
 * @author: Wang Zhihua
 * @date: 2022-10-08
 */
public class Solution {
    public int[] advantageCount(int[] nums1, int[] nums2) {

        int len = nums1.length;
        Item[] items = new Item[len];

        for (int i = 0; i < len; ++i) {
            items[i] = new Item();
            items[i].index = i;
            items[i].value = nums2[i];
        }

        Arrays.sort(nums1);
        Arrays.sort(items, Comparator.comparingInt(x -> x.value));

        int ite1 = -1;
        int ite2 = 0;
        while(++ite1 < len) {
            if (nums1[ite1] > items[ite2].value) {
                items[ite2].biggerNum = nums1[ite1];
                nums1[ite1] = -1;
                ++ite2;
            }
        }

        ite1 = -1;
        while(++ite1 < len) {
            if (nums1[ite1] != -1) {
                items[ite2++].biggerNum = nums1[ite1];
            }
        }

        Arrays.sort(items, Comparator.comparingInt(x -> x.index));

        for (int i = 0; i < len; ++i) {
            nums1[i] = items[i].biggerNum;
        }
        return nums1;
    }

    public static class Item {
        int value;
        int index;
        int biggerNum = -1;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        int[] nums1 = {2,7,11,15};
        int[] nums2 = {1,10,4,11};
        System.out.println("nums1: " + Arrays.toString(solution.advantageCount(nums1, nums2)));
        System.out.println("nums2: " + Arrays.toString(nums2));
        System.out.println();

        nums1 = new int[]{12,24,8,32};
        nums2 = new int[]{13,25,32,11};
        System.out.println("nums1: " + Arrays.toString(solution.advantageCount(nums1, nums2)));
        System.out.println("nums2: " + Arrays.toString(nums2));
        System.out.println();

        nums1 = new int[]{718967141,189971378,341560426,23521218,339517772};
        nums2 = new int[]{967482459,978798455,744530040,3454610,940238504};
        System.out.println("nums1: " + Arrays.toString(solution.advantageCount(nums1, nums2)));
        System.out.println("nums2: " + Arrays.toString(nums2));
        System.out.println();
    }
}
